import * as React from 'react';

import {IView} from '../types/IView';
import {IParentView} from '../types/IParentView';
import {IAttr} from '../types/IAttr';

import {IViewObject} from './IViewObject';
import AbsParentViewObject from './AbsParentViewObject';
import textViewObject from './TextViewObject';

export class LinkViewObject extends AbsParentViewObject<IParentView> implements IViewObject<IParentView> {

  viewType = 'link';

  attrs: IAttr[] = [
    {
      name: 'id',
      display: 'ID',
      type: 'string',
      required: true,
      defaultValGenerator: () => {
        return `linkView${this.viewIndex}`;
      }
    },
    {
      name: 'href',
      display: '链接',
      type: 'string',
      required: true,
      placeholder: 'http://xxx / ./xx.html / ...',
      defaultValGenerator: () => {
        return '';
      }
    },
    {
      name: 'target',
      display: '打开窗口',
      type: 'select',
      required: false,
      defaultValGenerator: () => {
        return '';
      },
      values: [
        {
          name: '_self',
          display: '当前窗口'
        },
        {
          name: '_blank',
          display: '新窗口'
        },
        {
          name: '_parent',
          display: '父窗口'
        },
        {
          name: '_top',
          display: '最顶级窗口'
        }
      ]
    },
    {
      name: 'className',
      display: 'class',
      type: 'string',
      required: false,
      defaultValGenerator: () => {
        return '';
      }
    },
    {
      name: 'title',
      display: '描述(title)',
      type: 'string',
      required: false,
      defaultValGenerator: () => {
        return `链接${this.viewIndex}`;
      }
    }
  ];

  create(designId: string): IParentView {
    return {
      id: this.generateId(),
      viewType: this.viewType,
      designId,
      style: {},
      attrVals: this.createAttrVals(this.attrs),
      children: [
        // 默认放一个文本上去, 不然空的内容, 不然不方便直接添加子组件
        textViewObject.create(designId)
      ]
    };
  }

  render(view: IParentView, refUpdater: (view: IView, ref: Element) => void): JSX.Element | null {
    const {style, attrVals} = view;

    const elemRefUpdater: React.Ref<Element> = el => refUpdater(view, el);
    const props: React.AnchorHTMLAttributes<HTMLElement> = {
      id: attrVals.id,
      href: attrVals.href,
      title: attrVals.title,
      className: attrVals.className,
      style: attrVals.className ? {} : style,
      onClick: this.preventClick
    };

    return (
      <a ref={elemRefUpdater} {...props}>
        {view.children.map(child => this.renderChild(child, refUpdater))}
      </a>
    );
  }

  private preventClick = (event: React.MouseEvent<any>) => {
    // 要阻止链接的点击事件, 不然就没办法选中这个组件了.
    event.preventDefault();
  }
}

const linkViewObject = new LinkViewObject();
export default linkViewObject;
